#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include "globle.h"

#define LOG_TAG "get_srio_data.c :"

static xdma_usr_dev *xdma_dev = NULL;
static int cmd_fd = -1;

static void sigfunc(int sig)
{
    LOG("recv a sig = %d,do clean flow!\r\n", sig);
    if (cmd_fd > 0)
    {
        close(cmd_fd);
        cmd_fd = -1;
    }
    low_speed_port_deinitial(xdma_dev);
    if (xdma_dev_deinit(xdma_dev) < 0)
    {
        LOGE(LOG_TAG" xdma_dev_deinit() failed,errno = %d\r\n", errno);
    }
    if (xdma_dev)
    {
        free(xdma_dev);
        xdma_dev = NULL;
    }
    LOG("terminal the programme!\r\n");
    exit(1);
}

int main(int argc, char **argv)
{
    int ret_val = -1;
    sig_t sighandler;

    sighandler = signal(SIGINT, sigfunc);
    if (sighandler == SIG_ERR)
    {
        LOGE(LOG_TAG"signal error,errno = %d\r\n", errno);
        goto err_out;
    }

    sighandler = signal(SIGTERM, sigfunc);
    if (sighandler == SIG_ERR)
    {
        LOGE(LOG_TAG"signal error,errno = %d\r\n", errno);
        goto err_out;
    }

    //show_version();

    xdma_dev = malloc(sizeof(xdma_usr_dev));
    if (!xdma_dev)
    {
        LOGE(LOG_TAG"malloc xdma_dev failed,errno = %d\r\n", errno);
        goto err_out;
    }
    memset(xdma_dev, '\0', sizeof(xdma_usr_dev));
    CHECK_ERR(LOG_TAG, "parse_arg", parse_arg(xdma_dev, argc, argv, "b:l:c:s:d:m:n:t:h") < 0, err_out); 
    CHECK_ERR(LOG_TAG, "xdma_dev_init", xdma_dev_init(xdma_dev) < 0, err_out);
  
    // dump_xdma_dev(xdma_dev);

    // cmd_fd = create_cmd_trans_channel();
    // if (cmd_fd < 0)
    // {
    //     LOGE(LOG_TAG"read cmd_channel_fd faild,errno = %d!\r\n", errno);
    //     goto err_out;
    // }
    //CHECK_ERR(LOG_TAG, "uart_can_net_cmd_port_initial", low_speed_port_initial(xdma_dev) < 0, err_out);

    while (1)
    {
     //   cmd_handle(cmd_fd, xdma_dev);
     //   printf("systerm running \r\n");
        sleep(10);
    }

err_out:
    if (cmd_fd > 0)
    {
        close(cmd_fd);
        cmd_fd = -1;
    }
    low_speed_port_deinitial(xdma_dev);
    if (xdma_dev_deinit(xdma_dev) < 0)
    {
        LOGE(LOG_TAG" xdma_dev_deinit() failed,errno = %d\r\n", errno);
    }
    if (xdma_dev)
    {
        free(xdma_dev);
        xdma_dev = NULL;
    }
    return 0;
}
